#!/usr/bin/env python2.5
# -*- coding: UTF-8 -*-  
 
from nmpacks.milonpy import NMdb
from google.appengine.ext import deferred
db=NMdb.db
#from google.appengine.api import users
#from google.appengine.ext import db
#from google.appengine.ext import deferred  
#------------------------------------------------------------------------------------------------------------------------- 
##class   nmModel(db.Model):  
##    @classmethod
##    def rpcEventual(cls):return db.create_rpc(read_policy=db.EVENTUAL_CONSISTENCY) 
##    @classmethod
##    def get_by_key_name_eventual(cls, keyname):return cls.get_by_key_name(keyname,  rpc=cls.rpcEventual())

##class DicPropertyEval(db.Property):
##    data_type = dict 
##    def get_value_for_datastore(self, model_instance): 
##        return db.Text(repr(super(DicPropertyEval, self).get_value_for_datastore(model_instance) ) ) 
##    def make_value_from_datastore(self, value):
##        if value is None:
##            return dict()
##        return eval(value) 
##    def default_value(self):
##        if self.default is None:return dict()
##        else:return super(DicPropertyEval, self).default_value().copy() 
##    def validate(self, value): 
###        if not isinstance(value, dict):
###            raise db.BadValueError('Property %s needs to be convertible '
###                                 'to a dict instance (%s) of class dict' % (self.name, value))
##        return super(DicPropertyEval, self).validate(value) 
##    def empty(self, value):return value is None  

 
class country_list(NMdb.nmModel): 
    lng       =db.StringProperty      (multiline=False, indexed=False)
    tags      =db.StringListProperty  (verbose_name='tag') #  required=False)   # default =None 
    flgs      =db.IntegerProperty     (indexed=False, required=False)   #,default=0,verbose_name='Flags hex') 
    #url      =db.StringProperty      (indexed=False,   default="/statistics/",  required=True)
    req_path  =db.StringProperty      (multiline=False, indexed=False, required=True, verbose_name='Request Path')
    title     =db.StringProperty      (multiline=True, indexed=False, required=True) #, choices=['choise1',  'choise2'])
    descr     =db.TextProperty        (indexed=False, required=False)  
    descrTxt  =db.TextProperty        (indexed=False, required=False) 
    hits      =db.IntegerProperty     (default=0, indexed=False)
    rating    =db.RatingProperty      (default=0, indexed=False)
    created   =db.DateTimeProperty    (auto_now_add=True)  
    modified  =db.DateTimeProperty    (auto_now=True , indexed=False)
    user      =db.UserProperty        (auto_current_user_add=True)  
## get(keys) here we are  deffered or rpc deadline ?
##Gets the entity or entities for the given key or keys, of any Model.
##Arguments:
##keys
##A Key object or a list of Key objects.
##rpc    
    @classmethod        
    def getAll(cls,limit=999, offset=0, tag=False, inclIntOrgs=True, sortFunct=False):
        q= cls.all().fetch(limit, offset)
        if not inclIntOrgs:q=[item for item in q if not 'Organizations' in item.tags ] 
        if tag: q=[item for item in q if tag in item.tags]
        if sortFunct: q.sort(cmp=sortFunct)  
        return q 
    @classmethod        
    def getAllWithTag(cls, tag):return cls.getAll(tag=tag, inclIntOrgs=True, sortFunct=lambda x,y: cmp(x.title, y.title))   
    @classmethod        
    def getLatest(cls):return cls.getAll(inclIntOrgs=False, sortFunct=lambda x,y: cmp(y.created, x.created))[16:]  
    @classmethod        
    def getAllSorted(cls):return cls.getAll(inclIntOrgs=False, sortFunct=lambda x,y: cmp(x.title, y.title))  
    @classmethod            
    def getPopular(cls):return cls.getAll(inclIntOrgs=False, sortFunct=lambda x,y: cmp(y.hits, x.hits) )[16:]
    @classmethod        
    def hitsIncrDefer(cls, keyname):
        deferred.defer(cls.hitsIncr, keyname) # _countdown=1, _name="hitsIncr")    
        #deferred.defer(cls.hitsIncr, keyname ,  _countdown=1)  
        #deferred.defer(do_something_expensive, "Hello, world!", 42, c=True, _countdown=100,  _name="fdfasdfas")
    @classmethod        
    def hitsIncr(cls, keyname):      
        item=cls.get_by_key_name_eventual(keyname)
        if item is None:
            pass
        else:
            item.hits +=1 
            item.put()
#        for item in q:
#            print str(item)
#            print item.title
            #db.delete(item)  
class DataStoreDic(NMdb.nmModel):
    dicVal = NMdb.DicPropertyEval(indexed=False)
    @classmethod  
    def set(cls,ck, dicVal, **kwargs):  
        newItem = cls(key_name=ck, dicVal=dicVal, **kwargs)   
        return newItem.put()     
    @classmethod        
    def get (cls, ck):  
        return cls.get_by_key_name_eventual(ck)  
     
class AppSetingsDic(DataStoreDic): 
    title = db.StringProperty (multiline=False, indexed=False)
    namespace = db.StringProperty (multiline=False)      
    
                    
